package com.camartsApp.controller;

import com.camartsApp.service.UserInfoService;
import com.camartsApp.Util.JwtUtils;
import com.camartsApp.Util.Response;
import com.camartsApp.common.ResultVO;
import com.camartsApp.common.UserInfoVO;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

import java.util.List;

@RestController
@RequestMapping("/userinfo")
public class UserInfoController {

    @Autowired
    private UserInfoService userService;

    @Autowired
    private JwtUtils jwtUtils;

    // 提取 token 并获取 userId 的工具方法
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        return null;
    }

    @GetMapping("/api/getId")
    public Long getUserId(HttpServletRequest request) {
        return getUserIdFromRequest(request);
    }


    /**
     * 获取当前用户的基础资料（头像、昵称、签名、关注数、粉丝数、获赞数）
     */
    @GetMapping("/api/me/profile")
    public ResultVO getUserProfile(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");
        }
        return userService.getUserProfile(userId);
    }



    // 获取头像
    @GetMapping("/api/avatar")
    public Object getAvatar(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token or missing user ID");
        }
        return userService.getAvatarById(userId);
    }

    // 获取昵称
    @GetMapping("/api/nickname")
    public Object getNickname(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token or missing user ID");
        }
        return userService.getNicknameById(userId);
    }

    // 获取关注数
    @GetMapping("/api/following-count")
    public Object getFollowingCount(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token or missing user ID");
        }
        return userService.getFollowingCountById(userId);
    }

    // 获取粉丝数
    @GetMapping("/api/followers-count")
    public Object getFollowersCount(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token or missing user ID");
        }
        return userService.getFollowersCountById(userId);
    }

    // 获取获赞数
    @GetMapping("/api/likes-count")
    public Object getLikesCount(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token or missing user ID");
        }
        return userService.getLikesCountById(userId);
    }

    // 获取个性签名
    @GetMapping("/api/signature")
    public Object getSignature(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token or missing user ID");
        }
        return userService.getSignatureById(userId);
    }

    @GetMapping("/api/status")
    public Object getStatus(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid token or missing user ID");
        }
        return userService.getStatusById(userId);
    }

    @GetMapping("/{targetUserId}/status")
    public Object getTargetUserStatus(@PathVariable("targetUserId") Long targetUserId) {
        // 查询目标用户状态
        return userService.getStatusById(targetUserId);
    }

    // 设置公开（仅当前用户）
    @PostMapping("/api/me/show-following")
    public ResultVO showHideFollowing(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");

        }
        return userService.setHideFollowing(userId, true);
    }

    // 设置私密（仅当前用户）
    @PostMapping("/api/me/hide-following")
    public ResultVO hideHideFollowing(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");

        }
        return userService.setHideFollowing(userId, false);
    }

    // 查询状态（任意用户）
    @GetMapping("/{userId}/status/hide-following")
    public ResultVO getHideFollowingStatus(@PathVariable("userId") Long userId) {
        return userService.getHideFollowingStatus(userId);
    }

    // ========== hide_followers：是否隐藏粉丝列表 ==========

    @PostMapping("/api/me/show-followers")
    public ResultVO showHideFollowers(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");

        }
        return userService.setHideFollowers(userId, true);
    }

    @PostMapping("/api/me/hide-followers")
    public ResultVO hideHideFollowers(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");

        }
        return userService.setHideFollowers(userId, false);
    }

    @GetMapping("/{userId}/status/hide-followers")
    public ResultVO getHideFollowersStatus(@PathVariable("userId") Long userId) {
        return userService.getHideFollowersStatus(userId);
    }

    // ========== hide_works：是否隐藏作品 ==========

    @PostMapping("/api/me/show-works")
    public ResultVO showHideWorks(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");

        }
        return userService.setHideWorks(userId, true);
    }

    @PostMapping("/api/me/hide-works")
    public ResultVO hideHideWorks(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");

        }
        return userService.setHideWorks(userId, false);
    }

    @GetMapping("/{userId}/status/hide-works")
    public ResultVO getHideWorksStatus(@PathVariable("userId") Long userId) {
        return userService.getHideWorksStatus(userId);
    }

    // ========== hide_likes：是否隐藏喜欢的作品 ==========

    @PostMapping("/api/me/show-likes")
    public ResultVO showHideLikes(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");

        }
        return userService.setHideLikes(userId, true);
    }

    @PostMapping("/api/me/hide-likes")
    public ResultVO hideHideLikes(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");
        }
        return userService.setHideLikes(userId, false);
    }

    @GetMapping("/{userId}/status/hide-likes")
    public ResultVO getHideLikesStatus(@PathVariable("userId") Long userId) {
        return userService.getHideLikesStatus(userId);
    }

    // 获取用户信息列表
    @GetMapping("/list")
    public ResultVO getUserInfoList(@RequestParam("ids") List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Response.FailResultByMsg("用户ID不能为空");
        }
        List<UserInfoVO> userList = userService.getUserInfoListByIds(ids);
        return Response.OkByData(userList);
    }

    /**
     * 获取当前用户发布的所有照片 ID
     */
    @GetMapping("/api/my/photos")
    public ResultVO getMyPhotoIds(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");
        }
        return userService.getPhotosByUserId(userId);
    }



    /**
     * 获取指定用户发布的所有照片 ID（不依赖 Token）
     */
    @GetMapping("/{userId}/photos")
    public ResultVO getOtherUserPhotoIds(@PathVariable("userId") Long userId) {
        if (userId == null || userId <= 0) {
            return Response.FailResultByMsg("无效的用户ID");
        }
        return userService.getPhotosByUserId(userId);
    }


    /**
     * 判断当前登录用户是否是目标用户本人
     */
    @GetMapping("/api/is-self/{targetUserId}")
    public ResultVO isSelf(@PathVariable("targetUserId") Long targetUserId, HttpServletRequest request) {
        Long currentUserId = getUserIdFromRequest(request);
        if (currentUserId == null) {
            return Response.FailResultByMsg("未登录");
        }
        return userService.isSelf(currentUserId, targetUserId);
    }


    /**
     * 删除指定照片（实际是设置 status = 2）
     */
    @DeleteMapping("/api/photo/{photoId}")
    public ResultVO deletePhoto(@PathVariable("photoId") Long photoId, HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");
        }
        return userService.deletePhoto(userId, photoId);
    }



    /**
     * 获取当前用户是否隐藏作品（从Token中获取userId）
     */
    @GetMapping("/api/whe-hide-works")
    public ResultVO getHideWorksStatus(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");
        }
        return userService.getHideWorksStatus(userId);
    }

    /**
     * 获取当前用户是否隐藏喜欢的作品（从Token中获取userId）
     */
    @GetMapping("/api/whe-hide-likes")
    public ResultVO getHideLikesStatus(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");
        }
        return userService.getHideLikesStatus(userId);
    }




    /**
     * 获取当前用户点赞过的所有照片（使用PhotoLikedDTO）
     */
    @GetMapping("/api/my/liked-photos")
    public ResultVO getMyLikedPhotos(HttpServletRequest request) {
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            return Response.FailResultByMsg("未登录");
        }
        return userService.getLikedPhotosByLoginUser(userId);
    }

    /**
     * 获取指定用户点赞过的所有照片（使用PhotoLikedDTO）
     */
    @GetMapping("/{userId}/Otherliked-photos")
    public ResultVO getOtherUserLikedPhotos(@PathVariable("userId") Long userId) {
        if (userId == null || userId <= 0) {
            return Response.FailResultByMsg("无效的用户ID");
        }
        return userService.getLikedPhotosByOtherUser(userId);
    }







}

